package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.exceptions.BusinessException;
import com.tanhua.server.intercepror.UserHolder;
import com.tanhua.utils.Constants;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class MovementsService {

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private CommentApi commentApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发布动态
     * @param imageContent  ：文件列表
     * @param movement      ：动态详情
     */
    public void movements(MultipartFile[] imageContent, Movement movement) throws IOException {
        //1、设置用户id
        movement.setUserId(UserHolder.getUserId());
        //2、设置发布时间
        movement.setCreated(System.currentTimeMillis());
        //3、将图片上传到阿里云oss，获取图片的地址
        List<String> medias = new ArrayList<>();
        for (MultipartFile file : imageContent) {
            String url = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());//文件名，输入流
            medias.add(url);
        }
        //4、设置媒体数据
        movement.setMedias(medias);
        //5、调用API操作mongodb数据库，完成保存，获取动态id
        String movementId = movementApi.save(movement);

        //当发布动态成功之后，发送MQ消息
        mqMessageService.sendAudiMessage(movementId); //动态id
    }

    //根据用户id查询用户发布的动态
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        //1、调用API根据用户id分页查询，动态列表  List<Movement>
        List<Movement> list = movementApi.findByUserId(userId,page,pagesize);
        //2、判断数据列表是否存在，不存在返回空PageResult
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //根据用户id，查询此用户的详情
        UserInfo info = userInfoApi.findById(userId);
        //3、循环List<Movement>集合，一个Movement构建一个vo对象
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : list) {                                            //10动态
            //获取动态详情UserInfo
            MovementsVo vo = MovementsVo.init(info, movement);//用户信息，动态对象
            //查询判断是否点赞(判断redis中点赞数据是否存在)
            String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
            String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
            Boolean hasKey = redisTemplate.opsForHash().hasKey(key, hashKey);
            if(hasKey) {
                vo.setHasLiked(1);
            }
            //构造是否喜欢的返回标志
            String loveKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
            Boolean hasLove = redisTemplate.opsForHash().hasKey(key, loveKey);
            if(hasLove) {
                vo.setHasLoved(1);
            }
            vos.add(vo);
        }
        //4、返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    //查询好友动态
    public PageResult findByFriendId(Integer page, Integer pagesize) {
        //1、获取查询的用户id条件
        Long friendId = UserHolder.getUserId();
        //2、调用API查询动态列表  List<Movement>
        List<Movement> list = movementApi.findByFriendId(friendId,page,pagesize);  //调用api + 1
        //3、判断是否存在，不存在返回空
        if(CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        return init(list,page,pagesize);
    }

    //查询推荐动态
    public PageResult findByRecommend(Integer page, Integer pagesize) {
        //1、从redis中获取推荐的数据
        String key = "MOVEMENTS_RECOMMEND_"+UserHolder.getUserId();
        String value = redisTemplate.opsForValue().get(key);  //2562,3639,2063,3448,2128,2597,2893,2333,3330,2642,2541,3002
        List<Movement> list = null;
        if(!StringUtils.isEmpty(value)) {
            //2、判断数据是否存在，存在调用API根据动态id列表，查询数据   List<Movement>
            String[] movementIds = value.split(",");
            list = movementApi.findByIds(movementIds,page,pagesize);
        }else {
            //3、如果数据不存在，构造模拟数据（从数据库中随机查询）      List<Movement>
            list = movementApi.randomMovement(pagesize);
        }
        //4、后续处理，环List<Movement>集合，一个Movement构建一个vo对象
        return init(list,page,pagesize);
    }

    //公共的处理方法
    private PageResult init(List<Movement> list,Integer page, Integer pagesize) {
        //a：获取list集合中所有的动态发布人的id    1,2,3,4,5,6
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        //b：调用一次userinfoapi，根据多个id查询用户信息   Map<userId,UserInfo> map (从数据库中查询的所有用户)
        Map<Long,UserInfo> map = userInfoApi.findByIds(userIds);  //调用API+1
        //4、循环List<Movement>集合，一个Movement构建一个vo对象
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : list) {                                            //循环list集合
            Long userId = movement.getUserId(); //动态发布人的id
            UserInfo info = map.get(userId);
            MovementsVo vo = MovementsVo.init(info, movement);
            //构造是否点赞的返回标志
            String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
            String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
            Boolean hasKey = redisTemplate.opsForHash().hasKey(key, hashKey);
            if(hasKey) {
                vo.setHasLiked(1);
            }
            //构造是否喜欢的返回标志
            String loveKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getUserId();
            Boolean hasLove = redisTemplate.opsForHash().hasKey(key, loveKey);
            if(hasLove) {
                vo.setHasLoved(1);
            }
            vos.add(vo);
        }
        //5、返回值
        return new PageResult(page,pagesize,0l,vos);
    }

    //根据id查询动态
    public MovementsVo findMovementById(String movementId) {
        //查询动态
        Movement movement =  movementApi.findById(movementId);
        //查询用户信息
        UserInfo userInfo = userInfoApi.findById(movement.getUserId());
        return MovementsVo.init(userInfo,movement);
    }

    //动态点赞
    public Integer like(String movementId) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、查询是否已经点赞，如果已点赞，抛出一个业务异常
        //redis中查询，或者MongoDB中查询
        Integer commentType = 1;
        Boolean hasComment = commentApi.hasComment(movementId,userId,commentType); //true表示存在
        if(hasComment) {
            throw new BusinessException(ErrorResult.likeError());
        }
        //3、未点赞，保存点赞数据到mongodb中
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(commentType);
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        //之前保存互动数据（评论--对此方法进行改造）
        Integer count = commentApi.save(comment);
        //4、保存点赞数据到redis中
        //操作hash的数据结构
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key,hashKey,"1");//redis的key，hashkey，hashvalue
        //5、返回

        //发送日志消息
        mqMessageService.sendLogMessage(userId,"0203","log.movement",movementId);

        return count;
    }

    //取消点赞数据
    public Integer dislike(String movementId) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、判断是否存在点赞数据，没有点赞，抛出异常
        Integer commentType = 1;  //1-点赞，2-评论，3-喜欢
        Boolean hasComment = commentApi.hasComment(movementId, userId, commentType);
        if(!hasComment) {
            throw new BusinessException(ErrorResult.disLikeError());
        }
        //3、调用API层删除点赞数据，返回最新的点赞总数
        Integer count = commentApi.delete(movementId, userId, commentType);
        //4、删除redis中的点赞数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key,hashKey);//redis中的key，需要删除的hashkey
        return count;
    }

    //喜欢
    public Integer love(String movementId) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、查询是否已经点赞，如果已点赞，抛出一个业务异常
        //redis中查询，或者MongoDB中查询
        Integer commentType = 3;
        Boolean hasComment = commentApi.hasComment(movementId,userId,commentType); //true表示存在
        if(hasComment) {
            throw new BusinessException(ErrorResult.loveError());
        }
        //3、未点赞，保存点赞数据到mongodb中
        Comment comment = new Comment();
        comment.setPublishId(new ObjectId(movementId));
        comment.setCommentType(commentType);
        comment.setUserId(userId);
        comment.setCreated(System.currentTimeMillis());
        //之前保存互动数据（评论--对此方法进行改造）
        Integer count = commentApi.save(comment);
        //4、保存点赞数据到redis中
        //操作hash的数据结构
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + userId;
        redisTemplate.opsForHash().put(key,hashKey,"1");//redis的key，hashkey，hashvalue
        //5、返回
        return count;
    }


    //取消喜欢
    public Integer unlove(String movementId) {
        //1、获取用户id
        Long userId = UserHolder.getUserId();
        //2、判断是否存在点赞数据，没有点赞，抛出异常
        Integer commentType = 3;  //1-点赞，2-评论，3-喜欢
        Boolean hasComment = commentApi.hasComment(movementId, userId, commentType);
        if(!hasComment) {
            throw new BusinessException(ErrorResult.disloveError());
        }
        //3、调用API层删除点赞数据，返回最新的点赞总数
        Integer count = commentApi.delete(movementId, userId, commentType);
        //4、删除redis中的点赞数据
        String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
        String hashKey = Constants.MOVEMENT_LOVE_HASHKEY + userId;
        redisTemplate.opsForHash().delete(key,hashKey);//redis中的key，需要删除的hashkey
        return count;
    }

    @DubboReference
    private VisitorsApi visitorsApi;

    /**
     * 查询首页-谁看过我
     *
     */
    public List<TodayBest> visitors() {
        //1、获取当前用户id
        Long userId = UserHolder.getUserId();
        //2、获取查看完整访客记录的时间  （在查看完成访客记录时，将时间存入redis）
        //获取并使用
        String key = Constants.VISITORS_USER+userId;
        String value = redisTemplate.opsForValue().get(key);
        Long time = 0l;
        if(!StringUtils.isEmpty(value)) {
            time = Long.valueOf(value);
        }
        //3、调用API查询  List<Visitors>
        List<Visitors> list = visitorsApi.findByUserId(userId,time);
        if(CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        //4、循环list集合，一个Visitors转化一个TodayBest
        //提取所有的访客id
        List<Long> ids = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        //查询所有访客数据，到map集合
        Map<Long, UserInfo> map = userInfoApi.findByIds(ids);
        List<TodayBest> vos = new ArrayList<>();
        for (Visitors visitors : list) {
            //获取访客的用户id
            Long visitorUserId = visitors.getVisitorUserId();
            //获取访客的用户信息
            UserInfo userInfo = map.get(visitorUserId);
            //构造vo
            TodayBest vo = TodayBest.init(userInfo, visitors);
            vos.add(vo);
        }
        //5、返回
        return vos;
    }
}
